<?php

namespace app\api\controller;

use app\api\lib\Alisms;
use app\api\model\Code;
use app\api\model\User as UserModel;
use app\api\model\UserCoupon as UserCouponModel;
use app\api\service\User as UserService;
use app\common\exception\BaseException;
use Firebase\JWT\JWT;

class User extends BaseController
{

    /**
     * Notice:获取jwt的token信息
     * Date  :2019/3/12
     */
    public static function getJwtToken($uid)
    {
        $key = config('jwt.key');
        $payload = [
            'lat' => config('jwt.lat'),
            'nbf' => config('jwt.nbf'),
            'exp' => config('jwt.exp'),
            'uid' => $uid,
        ];

        $jwtToken = JWT::encode($payload, $key);

        return $jwtToken;

    }

    /**
     * 用户登录接口
     */
    public function login()
    {

//        $model = new UserModel();
//        var_dump(11);
//        $user_id = $model->login($this->request->post());
//        var_dump($user_id);
//        $token = $model->getToken();
//        var_dump($token);
//        return $this->renderSuccess(compact('user_id', 'token'));
//        $data = input();
//        $username = 15617906676;
//        $username = $data['phone'];
        $username = 15617906676;
        $data['password'] = 123456;
        $password = md5(sha1($data['password']));
        $res = db('user')->where('username', $username)->select();
        if ($res == NULL) {
            return json(['code' => 401, 'msg' => '该手机号未注册']);
        }
        $res = db('user')->where('username', $username)->find();
        if ($password != $res['password']) {
            return json(['code' => 401, 'msg' => '密码错误,请重试']);
        } else {
            $data = $this::getJwtToken($res['id']);
            return json(['code' => 200, 'data' => $data, 'msg' => '登录成功']);
        }
    }


    /**
     * 用户注册接口
     */
    public function reg()
    {
        $data = $this->request->param();
        $phone = $data['phone'];
        $password = $data['password'];
        $repassword = $data['repassword'];
        $code = $data['code'];
        $source = '用户';
        $username = $phone;
        $nickname = $phone;
        $power = '2';
        $status = '1';
        //用户主页ID
        $identification = 1234567;
        $invitation_code = $data['invitation_code'];
        $list = [
            'source' => $source,
            'phone' => $phone,
            'password' => md5(sha1($password)),
            'username' => $username,
            'nickname' => $nickname,
            'power' => $power,
            'status' => $status,
            'identification' => $identification,
            'invitation_code' => rand(000000, 999999)
        ];

        if (empty($phone) || empty($password) || empty($repassword)) {
            return json(['code' => 401, 'msg' => '用户名或密码不能为空']);
        }
        if ($password != $repassword) {
            return json(['code' => 401, 'msg' => '两次密码输入不一致']);
        }
        $codes = db('code')->where('mobile', $phone)->field('code')->find();

        if ($code != $codes['code']) {
            return json(['code' => 401, 'msg' => '验证码错误']);
        }
        $times = db('code')->where('mobile', $phone)->where('type', 2)->field('dead_line')->find();
        $timee = strtotime($times['dead_line']);
        if (time() > $timee) {
            return json(['code' => 401, 'msg' => '验证码已过期']);
        }
        if (db('user')->where('phone', $phone)->find()) {
            return json(['code' => 401, 'msg' => '该手机号已注册']);
        }

        $invitation_code = 456789;
        //判断用户邀请码是否正确
        $recode = db('user')->where('invitation_code', $invitation_code)->field('invitation_code,id')->find();
        if ($recode != null) {
            $scores = db('score')->where('user_id', $recode['id'])->field('user_score')->find();
            //邀请码正确赠送 300 积分
            $score = $scores['user_score'] + 300;
            db('score')->where('user_id', $recode['id'])->update(['user_score' => $score]);
        } else {
            return $this->renderSuccess(compact('recode'), '邀请码错误');
        }
        $res = db('user')->insert($list);
        if ($res) {
            return json(['code' => 200, 'msg' => '注册成功']);
        }
    }

    /**
     * 注册发送验证码
     */
    public function sendcode()
    {
//        $mobile = $this->request->param('phone');
        $mobile = 15617906676;
        if (empty($mobile)) {
            return $this->renderError('手机号不能为空');
        }
//        if (session('user_id')) {
//            $type = 2;
//        } else {
//            $type = 1;
//        }
        $type = 1;
        $code = rand(000000, 999999);
        $this->makecode($mobile, $type, $code);
//        $sign = config('alisms.SignName');
//        $code = config('alisms.TemplateCode');
//        $ak = config('alisms.AccessKeyId');
//        $sk = config('alisms.Secret');
//        // 请求的参数
//        $params = [
//            'phone' => $mobile,
//            'sign' => $sign,
//            'code' => $code,
//            'param' => json_encode([
//                'name' => "测试名称",
//                'number' => 2334
//            ])
//        ];
//        var_dump($params);
        $res = Alisms::sendCode($mobile, $code);
        var_dump($res);
        if ($res == true) {
            return json_encode(['code' => 200, 'msg' => "验证码发送成功~"]);
        }
    }

    /**
     * 验证码生成保存到数据库
     */
    public function makecode($mobile, $type, $code)
    {
        $user_id = session('user_id');
        $user_id = 1;
        $list = [
            'user_id' => $user_id,
            'mobile' => $mobile,
            'type' => $type,
            'code' => $code,
            'sms' => 1,
//            'dead_line' => date('Y-m-d H:i:s', strtotime('+5minute'))
            'dead_line' => time() + 300
        ];
        db('code')->insert($list);
    }


    /**
     * 当前用户详情
     * @return array|\think\response\Json
     * @throws BaseException
     */
    public function info()
    {

        // 当前用户信息
        $userInfo = UserService::getCurrentLoginUser(true);
        return $userInfo;
        // 获取用户头像
        // $userInfo['avatar'];
        // // 获取会员等级
        // $userInfo['grade'];
        // $id = session('user_id');
        $id = 1;
        $infos = new UserModel();
        $userInfo = $infos->getUserinfo($id);
        return $this->renderSuccess(compact('userInfo'));
    }

    /**
     * 更改用户基本信息
     *
     */
    public function updateUser()
    {
        // $userInfo = UserService::getCurrentLoginUser(true);
        $id = 1;
        $userlist = $this->request->param();
        $data = $userlist;
        $lists = new UserModel();
        $upuserInfo = $lists->updUser($id, $data);
        return $this->renderSuccess(compact('upuserInfo'));
    }

    /**
     * 修改手机号
     *
     */
    public function updPhone()
    {
        $id = 1;
        $data = $this->request->param();
        $data['phone'] = 123456;
        $codes = new Code();
        $code = $codes::where('user_id', 0)->where('type', 2)->find();
        if ($code['code'] != $data['code']) {
            return json(['code' => 401, 'msg' => '验证码错误']);
        }
        $times = db('code')->where('user_id', 0)->where('type', 2)->field('dead_line')->find();
        $timee = strtotime($times['dead_line']);
        var_dump(time());
        var_dump($timee);
        if (time() > $timee) {
            return json(['code' => 401, 'msg' => '验证码已过期']);
        }
        var_dump(111);
        $res = UserModel::where('id', $id)->update(['phone' => $data['phone']]);
        return $this->renderSuccess(compact('res'));

    }

    /**
     * 修改密码
     *
     */
    public function uppassword()
    {

    }
    // public function getFans()
    // {
    //     $ids = UserModel::where('id', 1)->field('fans')->find()->toArray();
    //     $id = explode(",", $ids['fans']);
    //     var_dump($id);
    //     $count = count($id);
    //     var_dump($count);
    // }

    /**
     * 账户资产
     * @return array|\think\response\Json
     * @throws BaseException
     */
    public function assets()
    {
        // 当前用户信息
        $userInfo = UserService::getCurrentLoginUser(true);
        // 用户优惠券模型
        $model = new UserCouponModel;
        // 返回数据
        return $this->renderSuccess([
            'assets' => [
                'balance' => $userInfo['balance'],  // 账户余额
                'points' => $userInfo['points'],    // 会员积分
                'coupon' => $model->getCount($userInfo['user_id']),    // 优惠券数量(可用)
            ]
        ]);
    }

    /**
     * 用户粉丝
     *
     */
    public function getFans()
    {
        $id = 1;
        $fans = new UserModel();
        $list = $fans->getFan($id);
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 用户关注
     *
     */
    public function getFollow()
    {
        $id = 1;
        $follows = new UserModel();
        $list = $follows->getGuanzhu($id);
        return $this->renderSuccess(compact('list'));
    }

    /**
     * 我的礼物
     *
     */
    public function getGift()
    {
        bushi zhege
    }

    /**
     * 账号与安全
     *
     */
    public function getPhone()
    {
        $user_id = session('user_id');
        $user_id = 6;
        $info = UserModel::where('id', $user_id)->field('phone')->find();
        return $this->renderSuccess(compact('info'));
    }

}